<template>
  <div style="background-color: white; min-height: 100vh; padding: 20px 0;">
    <el-container style="min-height: 100vh;">
      <el-main style="display: flex; justify-content: center; padding: 20px;">
        <el-form :model="ruleForm" ref="ruleFormRef" label-width="120px" style="width: 800px; max-width: 95%;">
          <!-- 步骤条 -->
          <div style="margin-bottom: 30px;">
            <el-steps :active="2" align-center>
              <el-step title="步骤1" description="填写公司认证信息"></el-step>
              <el-step title="步骤2" description="签订入驻合同"></el-step>
              <el-step title="步骤3" description="公司申请入驻成功"></el-step>
            </el-steps>
          </div>

          <!-- 标题 -->
          <div style="text-align: center; margin-bottom: 30px;">
            <h1 style="margin-bottom: 10px;">签订入驻合同</h1>
            <p style="color: #666;">请上传6份合同文件，其中"其他合同"可上传多个文件</p>

            <!-- 显示接收到的公司信息 -->
            <div v-if="companyInfo.name"
              style="margin-top: 15px; padding: 10px; background: #f5f7fa; border-radius: 4px;">
              <p style="margin: 5px 0; color: #409EFF;">
                <strong>公司名称:</strong> {{ companyInfo.name }}
              </p>
              <p style="margin: 5px 0; color: #409EFF;">
                <strong>统一信用代码:</strong> {{ companyInfo.creditCode }}
              </p>
              <p v-if="companyInfo.id" style="margin: 5px 0; color: #67C23A;">
                <strong>公司ID:</strong> {{ companyInfo.id }}
              </p>
            </div>

            <!-- 加载状态 -->
            <div v-if="loadingCompanyInfo" style="margin-top: 15px;">
              <el-icon class="is-loading" style="font-size: 20px; color: #409EFF;">
                <Loading />
              </el-icon>
              <p style="color: #409EFF; margin-top: 5px;">正在获取公司信息...</p>
            </div>

            <!-- 错误状态 -->
            <div v-if="companyInfoError"
              style="margin-top: 15px; padding: 10px; background: #fff6f6; border: 1px solid #ffccc7; border-radius: 4px;">
              <p style="margin: 5px 0; color: #f5222d;">
                <strong>错误:</strong> {{ companyInfoError }}
              </p>
              <el-button type="primary" size="small" @click="goBackToRegister">
                返回注册页面
              </el-button>
            </div>
          </div>

          <!-- 合同表单区域 -->
          <div v-if="companyInfo.id" style="max-height: 60vh; overflow-y: auto; padding: 0 10px;">
            <!-- 6个合同上传组 -->
            <div v-for="(contract, index) in ruleForm.contracts" :key="index" class="contract-group">
              <el-form-item :label="`合同${index + 1}类型`" :prop="`contracts.${index}.type`"
                :rules="{ required: true, message: '请选择合同类型', trigger: 'change' }">
                <el-select v-model="contract.type" placeholder="请选择合同类型" style="width: 100%;"
                  @change="resetContractFiles(index)" clearable>
                  <el-option v-for="item in contractTypes" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
              </el-form-item>

              <el-form-item :label="`合同${index + 1}文件`" :prop="`contracts.${index}.files`" :rules="[
                { required: true, message: '请上传合同文件', trigger: 'change' },
                { validator: validateContractFiles, trigger: 'change' }
              ]">
                <el-upload
                  class="contract-upload"
                  :action="uploadUrl"
                  :data="getUploadData(index)"
                  :on-success="(res, file) => handleUploadSuccess(index, res, file)"
                  :on-error="(err, file) => handleUploadError(index, err, file)"
                  :before-upload="(file) => beforeUpload(file, index)"
                  :on-change="(file, fileList) => handleFileChange(index, file, fileList)"
                  :on-remove="(file) => handleFileRemove(index, file)"
                  :file-list="contract.files"
                  :limit="contract.type === 'other' ? 5 : 1"
                  accept=".pdf,.doc,.docx,.jpg,.jpeg,.png"
                  :auto-upload="true"
                  :ref="el => setUploadRef(el, index)"
                  multiple
                >
                  <el-button type="primary" size="small">
                    <i class="el-icon-upload"></i> 选择文件
                  </el-button>

                  <template #tip>
                    <div class="upload-tip">{{ getUploadTip(contract.type) }}</div>
                  </template>
                </el-upload>

                <div v-if="contract.fileUrls.length > 0" class="preview-container">
                  <div v-for="(fileInfo, i) in contract.fileUrls" :key="i" class="preview-item">
                    <el-tag closable @close="removeFileUrl(index, i)" @click="previewFile(fileInfo.url)">
                      {{ fileInfo.name }}
                    </el-tag>
                  </div>
                </div>
              </el-form-item>

              <el-divider v-if="index < 5" />
            </div>
          </div>

          <!-- 提交按钮区域 -->
          <el-form-item v-if="companyInfo.id" class="submit-area">
            <el-button type="primary" size="medium" @click="submitForm" :loading="loading"
              :disabled="loading || !allFilesUploaded">
              {{ loading ? '提交中...' : '提交申请' }}
            </el-button>
            <el-button @click="goBack" size="medium">返回上一步</el-button>
          </el-form-item>
        </el-form>
      </el-main>
    </el-container>
  </div>
</template>

<script>
import { ref, reactive, onMounted, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Loading } from '@element-plus/icons-vue'
import axios from 'axios'

export default {
  name: 'ContractView',
  components: { Loading },
  setup() {
    const route = useRoute()
    const router = useRouter()
    const ruleFormRef = ref(null)
    const loading = ref(false)
    const loadingCompanyInfo = ref(false)
    const companyInfoError = ref('')
    const uploadRefs = ref([])

    const companyInfo = ref({
      id: null,
      name: '',
      creditCode: ''
    })

    const ruleForm = reactive({
      contracts: Array.from({ length: 6 }, () => ({
        type: '',
        files: [],
        fileUrls: [] // { name, url }
      }))
    })

    const contractTypes = [
      { value: 'lease', label: '租赁合同', fileType: 5 },
      { value: 'settlement', label: '入驻合同', fileType: 6 },
      { value: 'damage', label: '损毁合同', fileType: 7 },
      { value: 'property', label: '物业合同', fileType: 8 },
      { value: 'service', label: '服务合同', fileType: 9 },
      { value: 'other', label: '其他合同', fileType: 10 }
    ]

    // 从环境变量获取基础地址，拼接相对路径
   const uploadUrl = `${import.meta.env.VITE_API_BASE_URL}/api/company/upload`;

    // 计算属性：检查所有文件是否已上传
    const allFilesUploaded = computed(() => {
      return ruleForm.contracts.every(contract => {
        if (!contract.type) return true // 未选择类型的不检查
        return contract.files.length > 0 && contract.fileUrls.length === contract.files.length
      })
    })

    // 获取上传参数（与后端接口对齐）
    const getUploadData = (index) => {
      const contract = ruleForm.contracts[index]
      const fileTypeObj = contractTypes.find(t => t.value === contract.type)
      return {
        companyId: companyInfo.value.id,
        fileType: fileTypeObj ? fileTypeObj.fileType : null
      }
    }

    // 返回注册页面
    const goBackToRegister = () => {
      router.push('/register')
    }

    // 根据公司名和信用代码获取公司ID
    const fetchCompanyId = async (companyName, creditCode) => {
      try {
        loadingCompanyInfo.value = true
        companyInfoError.value = ''
        
        const response = await axios.get(`${import.meta.env.VITE_API_BASE_URL}/api/company/getId`, {
         params: { 
         name: companyName, 
         creditCode: creditCode 
        }
      })

        if (response.data.code === 200 && response.data.data) {
          companyInfo.value.id = response.data.data
          ElMessage.success('公司信息加载成功')
        } else {
          throw new Error(response.data.message || '未找到公司信息')
        }
      } catch (error) {
        console.error('获取公司ID失败:', error)
        companyInfoError.value = error.response?.data?.message || error.message || '获取公司信息失败'
        ElMessage.error('获取公司信息失败: ' + companyInfoError.value)
      } finally {
        loadingCompanyInfo.value = false
      }
    }

    // 从路由参数获取公司信息
    const fetchCompanyInfo = () => {
      const companyName = route.params.companyName || route.query.companyName
      const creditCode = route.params.creditCode || route.query.creditCode

      if (!companyName || !creditCode) {
        companyInfoError.value = '未接收到公司信息参数'
        ElMessage.warning('未找到公司信息，请返回上一步重新填写')
        return
      }

      companyInfo.value = {
        name: companyName,
        creditCode: creditCode,
        id: null
      }

      // 获取公司ID
      fetchCompanyId(companyName, creditCode)
    }

    // 在组件加载后读取参数
    onMounted(() => {
      fetchCompanyInfo()
    })

    // 设置上传组件引用
    const setUploadRef = (el, index) => {
      if (el) uploadRefs.value[index] = el
    }

    // 重置合同文件
    const resetContractFiles = (index) => {
      ruleForm.contracts[index].files = []
      ruleForm.contracts[index].fileUrls = []
    }

    // 验证合同文件
    const validateContractFiles = (rule, value, callback) => {
      const fieldPath = rule.field.split('.')
      const index = parseInt(fieldPath[1])
      const contract = ruleForm.contracts[index]

      if (!contract.type) return callback(new Error('请先选择合同类型'))
      if (contract.files.length === 0) return callback(new Error('请上传合同文件'))
      if (contract.type !== 'other' && contract.files.length > 1) return callback(new Error('该合同类型只能上传一个文件'))

      callback()
    }

    // 上传前校验
    const beforeUpload = (file, index) => {
      if (!companyInfo.value.id) {
        ElMessage.error('请先获取公司信息')
        return false
      }

      const contract = ruleForm.contracts[index]
      const fileExtension = file.name.split('.').pop().toLowerCase()
      const allowedExtensions = ['pdf', 'doc', 'docx', 'jpg', 'jpeg', 'png']
      const isValidType = allowedExtensions.includes(fileExtension)
      const isLt5M = file.size / 1024 / 1024 < 5

      if (!isValidType) {
        ElMessage.error('只支持PDF、Word、图片格式的文件!')
        return false
      }
      if (!isLt5M) {
        ElMessage.error('文件大小不能超过5MB!')
        return false
      }
      if (contract.type !== 'other' && contract.files.length > 1) {
        ElMessage.error('该合同类型只能上传一个文件!')
        return false
      }
      if (contract.type === 'other' && contract.files.length >= 5) {
        ElMessage.error('其他合同最多上传5个文件!')
        return false
      }

      return true
    }

    // 文件变更处理（维护 el-upload 的 fileList）
    const handleFileChange = (index, file, fileList) => {
      const contract = ruleForm.contracts[index]
      contract.files = contract.type !== 'other' ? fileList.slice(-1) : fileList.slice(-5)
    }

    // 文件移除处理（精准移除对应 file & 预览）
    const handleFileRemove = (index, file) => {
      const contract = ruleForm.contracts[index]
      // 从 fileList 移除对应 uid
      contract.files = contract.files.filter(f => f.uid !== file.uid)
      // 从预览移除（按名称或 URL 兜底）
      contract.fileUrls = contract.fileUrls.filter(f => f.name !== (file.name || f.name))
    }

    // 上传成功处理（与后端 Result<FileOssVO> 对齐）
    const handleUploadSuccess = (index, response, file) => {
      if (response && response.code === 200 && response.data) {
        const contract = ruleForm.contracts[index]
        contract.fileUrls.push({
          name: response.data.fileName || file.name,
          url: response.data.fileUrl
        })
        ElMessage.success(`合同${index + 1}文件上传成功`)
      } else {
        ElMessage.error(response?.message || '文件上传失败')
        // 移除上传失败的文件
        const contract = ruleForm.contracts[index]
        contract.files = contract.files.filter(f => f.uid !== file.uid)
      }
    }

    // 上传错误处理（仅影响当前分组）
    const handleUploadError = (index, error, file) => {
      console.error('上传错误:', error)
      ElMessage.error('文件上传失败: ' + (error?.message || '未知错误'))
      const contract = ruleForm.contracts[index]
      contract.files = contract.files.filter(f => f.uid !== file.uid)
    }

    // 提交表单
    const submitForm = async () => {
      if (!companyInfo.value.id) {
        ElMessage.error('公司信息不完整，无法提交')
        return
      }

      try {
        await ruleFormRef.value.validate()
      } catch (error) {
        ElMessage.error('请填写完整的合同信息')
        return
      }

      loading.value = true
      try {
        const response = await axios.post(
       `${import.meta.env.VITE_API_BASE_URL}/api/company/applications/submit`,
       { companyId: companyInfo.value.id },
       { headers: { 'Content-Type': 'application/json' } }
         )

        if (response.data.code === 200) {
          ElMessage.success('入驻申请提交成功')
          router.push({
            path: '/success',
            query: { 
              companyId: companyInfo.value.id, 
              companyName: companyInfo.value.name 
            }
          })
        } else {
          throw new Error(response.data.message || '提交失败')
        }
      } catch (error) {
        console.error('申请提交错误:', error)
        ElMessage.error('提交失败: ' + (error.response?.data?.message || error.message))
      } finally {
        loading.value = false
      }
    }

    // 移除文件URL（点 tag 的 X）
    const removeFileUrl = (index, urlIndex) => {
      ruleForm.contracts[index].fileUrls.splice(urlIndex, 1)
      // 同步删除 fileList 中对应文件（按名称匹配）
      const removed = ruleForm.contracts[index].fileUrls[urlIndex]
      if (removed) {
        ruleForm.contracts[index].files = ruleForm.contracts[index].files.filter(f => f.name !== removed.name)
      }
    }

    // 预览文件
    const previewFile = (url) => {
      if (url) window.open(url, '_blank')
    }

    // 上传提示
    const getUploadTip = (type) => {
      return type === 'other' 
        ? '可上传多个文件(最多5个)，支持PDF、Word、图片格式，单个文件不超过5MB'
        : '只能上传一个文件，支持PDF、Word、图片格式，文件不超过5MB'
    }

    // 返回上一步
    const goBack = () => router.go(-1)

    return {
      ruleFormRef,
      ruleForm,
      contractTypes,
      uploadUrl,
      loading,
      loadingCompanyInfo,
      companyInfo,
      companyInfoError,
      allFilesUploaded,
      setUploadRef,
      getUploadData,
      resetContractFiles,
      validateContractFiles,
      beforeUpload,
      handleFileChange,
      handleFileRemove,
      handleUploadSuccess,
      handleUploadError,
      submitForm,
      removeFileUrl,
      previewFile,
      getUploadTip,
      goBack,
      goBackToRegister
    }
  }
}
</script>

<style scoped>
.contract-group {
  margin-bottom: 20px;
  padding: 15px;
  background-color: #f9f9f9;
  border-radius: 4px;
}

.upload-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 7px;
  line-height: 1.5;
}

.preview-container {
  margin-top: 10px;
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.preview-item .el-tag {
  cursor: pointer;
  max-width: 200px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.submit-area {
  margin-top: 30px;
  text-align: center;
  padding-top: 20px;
  border-top: 1px solid #eee;
}

.el-divider {
  margin: 20px 0;
}

h1 {
  color: #333;
  font-size: 24px;
  margin: 0;
}

::-webkit-scrollbar { width: 6px; }
::-webkit-scrollbar-thumb { background-color: #c1c1c1; border-radius: 3px; }
::-webkit-scrollbar-track { background-color: #f1f1f1; }
</style>